package com.yunqi.autovender.activity;

import android.arch.lifecycle.Observer;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.yunqi.autovender.R;
import com.yunqi.autovender.adapter.ShoppingCarAdapter;
import com.yunqi.autovender.databinding.ActivityShoppingCarBinding;
import com.yunqi.autovender.model.DrugInfo;
import com.yunqi.autovender.model.GlobalData;
import com.yunqi.autovender.util.TextStyleUtil;
import com.yunqi.autovender.view.PaymentDialog;
import com.yunqi.autovender.view.SelectPayTypeDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import google.architecture.common.base.BaseActivity;
import google.architecture.common.util.ToastUtils;
import google.architecture.coremodel.callback.ShoppingCarCallback;
import google.architecture.coremodel.callback.ShoppingCarItemClickCallback;
import google.architecture.coremodel.constant.ARGConstant;
import google.architecture.coremodel.constant.ARouterPath;
import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.constant.EventCode;
import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.navigator.ShoppingCarNavigator;
import google.architecture.coremodel.rx.RxEvent;
import google.architecture.coremodel.viewmodel.ShoppingCarViewModel;

/**
 * 购物车界面
 */
@Route(path = ARouterPath.ShoppingCarAct)
public class ShoppingCarActivity extends BaseActivity implements ShoppingCarNavigator {

    ActivityShoppingCarBinding activityShoppingCarBinding;
    ShoppingCarViewModel shoppingCarViewModel;
    ShoppingCarAdapter shoppingCarAdapter;
    PaymentDialog mPaymentDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityShoppingCarBinding = DataBindingUtil.setContentView(this, R.layout.activity_shopping_car);
        initRecyclerView();
        activityShoppingCarBinding.setShoppingCarViewModel(shoppingCarViewModel);
        activityShoppingCarBinding.setCallback(mShoppingCarCallback);
        subscribeToModel(shoppingCarViewModel);
        initRxBus();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unSubscribeRxBus();
    }

    private void initRecyclerView() {
        shoppingCarAdapter = new ShoppingCarAdapter(shoppingCarItemClickCallback);
        shoppingCarViewModel = new ShoppingCarViewModel(this.getApplication());
        shoppingCarViewModel.setShoppingCarNavigator(this);
        activityShoppingCarBinding.setRecyclerAdapter(shoppingCarAdapter);
        //构造器中，第一个参数表示列数或者行数，第二个参数表示滑动方向,瀑布流
    }

    ShoppingCarItemClickCallback shoppingCarItemClickCallback = new ShoppingCarItemClickCallback() {

        @Override
        public void onClick(ShoppingCarItem item, int action) {
            switch (action) {
                case ShoppingCarItemClickCallback.ACTION_ITEM_REMOVE:
                    shoppingCarViewModel.deleteShoppingCar(item);
                    shoppingCarAdapter.removeData(item.getPosition());
                    break;
                case ShoppingCarItemClickCallback.ACTION_ADD_COUNT:
                    //超过库存数，直接return
                    if (item.getCount() >= item.getStackCount()) {
                        return;
                    }
                    item.setCount(item.getCount() + 1);
                    shoppingCarViewModel.updateShoppingCar(item, ShoppingCarViewModel.ACTION_ADD);
                    shoppingCarAdapter.updateData(item.getPosition());
                    break;
                case ShoppingCarItemClickCallback.ACTION_DEL_COUNT:
                    //小于或者等于1时，直接return
                    if (item.getCount() <= 1) {
                        return;
                    }
                    item.setCount(item.getCount() - 1);
                    shoppingCarViewModel.updateShoppingCar(item, ShoppingCarViewModel.ACTION_REDUCE);
                    shoppingCarAdapter.updateData(item.getPosition());
                    break;
            }

        }
    };

    /**
     * 订阅数据变化来刷新UI
     *
     * @param model
     */
    private void subscribeToModel(final ShoppingCarViewModel model) {
        //观察数据变化来刷新UI
        model.getLiveObservableData().observe(this, new Observer<List<ShoppingCarItem>>() {
            @Override
            public void onChanged(@Nullable List<ShoppingCarItem> shoppingCarItems) {
                Log.i(TAG, "subscribeToModel onChanged onChanged");
                model.setUiObservableData(shoppingCarItems);
                shoppingCarAdapter.setShoppingCarItemList(shoppingCarItems);
            }
        });
    }

    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    private ShoppingCarCallback mShoppingCarCallback = new ShoppingCarCallback() {

        @Override
        public void onClick(int action) {
            switch (action) {
                case ACTION_PAYMENT_CLICK:
                    SelectPayTypeDialog selectPayTypeDialog = new SelectPayTypeDialog(ShoppingCarActivity.this, new SelectPayTypeDialog.PayTypeCallback() {
                        @Override
                        public void onSelectPayType(int payType) {
                            String terNo = (String) GlobalData.getInstance().getData(ARGConstant.ARG_TERNO);
                            List<DrugInfo> dugInfoList = new ArrayList<>();
                            double totalPrice = 0;
                            for (ShoppingCarItem item : shoppingCarViewModel.uiObservableData.get()) {
                                DrugInfo info = new DrugInfo();
                                info.setDrugName(item.getTitle());
                                info.setPlanId(item.getId());
                                info.setDrugPrice(item.getPrice());
                                info.setQuantity(item.getCount());
                                double prices = item.getPrice() * item.getCount();
                                totalPrice = add(totalPrice, prices);
                                dugInfoList.add(info);
                            }
                            String drugInfos = new Gson().toJson(dugInfoList);
                            shoppingCarViewModel.creatTrade(terNo, payType, drugInfos);
                            mPaymentDialog = new PaymentDialog(ShoppingCarActivity.this, totalPrice);
                            mPaymentDialog.show();
                        }
                    });
                    selectPayTypeDialog.show();
                    break;
                case ACTION_CLEAR_SHOP_CAR:
                    shoppingCarViewModel.clearData(false);
                    break;
                case ACTION_BACK:
                    finish();
                    break;


            }
        }
    };

    @Override
    public void onClearAllData(boolean isFinish) {
        if (isFinish) {
            finish();
        } else {
            shoppingCarAdapter.clear();
        }
    }

    @Override
    public void showImage(Bitmap bitmap) {
        mPaymentDialog.setQRCode(bitmap);
    }

    @Override
    public void showError(int code, String errorMsg) {
        ToastUtils.showShortToast(errorMsg);
        switch (code) {
            case ErrorCode.FAILED_CREATE_ORDER:
            case ErrorCode.FAILED_CREATE_QRCODE:
                mPaymentDialog.hideLoading();
                break;
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    protected void onCall(RxEvent event) {
        switch (event.code) {
            case EventCode.PUSH_PAY_SUCCESS:
                if (mPaymentDialog != null && mPaymentDialog.isShowing()) {
                    mPaymentDialog.dismiss();
                }
                shoppingCarViewModel.clearData(true);
                break;
        }
    }

    @Override
    protected void onCountDownFinished() {
        if (shoppingCarViewModel.totalCountField.get() > 0) {
            shoppingCarViewModel.clearData(true);
        }
        else {
            finish();
        }
    }

    @Override
    protected void onCountDownTick(int seconds) {
        if (seconds <= mCountDown /2) {
            shoppingCarViewModel.countDownShow.set(true);
            String formatStr = String.format(getString(R.string.txt_count_down2), seconds);
            int start = formatStr.lastIndexOf("，");
            int end = formatStr.lastIndexOf("秒");
            TextStyleUtil.highStrWithIndex(activityShoppingCarBinding.txtCountDown, formatStr, start + 1, end);
        } else {
            shoppingCarViewModel.countDownShow.set(false);
        }
    }

    @Override
    protected boolean isStartCountDown() {
        return true;
    }
}
